package com.gome.haotingtest001;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class ScrollingActivity extends AppCompatActivity {

    private TextView mTextview;

    ListView providersListView;
    LocationManager lm;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mTextview = (TextView) findViewById(R.id.textview);
        providersListView = (ListView) findViewById(R.id.providers);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        testLocation();
    }


    /**
     * Test the location provider
     */
    private void testLocation() {
        mTextview.setText("start location ...");


        //获取系统的LocationManager对象
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


        //********************* 方式1： 使用criteria 过滤并获取制定条件的provider *******************//
        //创建一个LocationProvider的过滤条件
        Criteria cri = new Criteria();
        cri.setAccuracy(2);
        //设置要求LocationProvider必须是免费的
        cri.setCostAllowed(false);
        //设置要求LocationProvider能提供高度信息
        cri.setAltitudeRequired(false);
        //设置要求LocationProvider能提供方向信息
        cri.setBearingRequired(false);

        //获取系统所有的LocationProvider的名称
        List<String> providerNames = lm.getProviders(cri, false);

        //********************* 方式2： 获取全部provider *******************//
        // List<String> providerNames = lm.getAllProviders();


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, providerNames);
        //使用ListView来显示所有可用的LocationProvider
        providersListView.setAdapter(adapter);


        // 制定provider
        LocationProvider loProvider = lm.getProvider(LocationManager.NETWORK_PROVIDER);


        mTextview.setText("gpsProvider: " + loProvider.getName());

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                mTextview.setText( mTextview.getText() + "\n && GPS location: " + location.getLatitude() + "\n" + getLocationString(location) + " && 精度:" + location.getAccuracy());
            }

            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                mTextview.setText(mTextview.getText() + "\n && Network location: " + location.getLatitude() + "\n" + getLocationString(location) + " && 精度:" + location.getAccuracy());

            }

            location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            if (location != null) {
                mTextview.setText(mTextview.getText() + "\n && Passive location: " + location.getLatitude() + "\n" + getLocationString(location) + " && 精度:" + location.getAccuracy());

            }
        }




    }



    private String getLocationString(Location loc) {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());


        List<Address> addresses = null;

        try {

            // Call the synchronous getFromLocation() method by passing in the lat/long values.

            addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);

        } catch (IOException e) {

            e.printStackTrace();

        }

        if (addresses != null && addresses.size() > 0) {

            Address address = addresses.get(0);

            // Format the first line of address (if available), city, and country name.

            return String.format("%s, %s, %s",

                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",

                    address.getLocality(),

                    address.getCountryName());
        }

        return null;
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
